package com.pdd.mall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pdd.mall.dto.BalanceOperationParam;
import com.pdd.mall.dto.UpdatePasswordParam;
import com.pdd.mall.dto.UpdateUserInfoParam;
import com.pdd.mall.dto.UserLoginParam;
import com.pdd.mall.dto.UserRegisterParam;
import com.pdd.mall.entity.Order;
import com.pdd.mall.entity.User;
import com.pdd.mall.mapper.OrderMapper;
import com.pdd.mall.mapper.UserMapper;
import com.pdd.mall.service.OrderService;
import com.pdd.mall.service.UserService;
import com.pdd.mall.util.JwtTokenUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    @Lazy
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public User register(UserRegisterParam param) {
        // 查询是否已有该用户
        User existUser = getUserByUsername(param.getUsername());
        if (existUser != null) {
            return null;
        }

        // 创建用户
        User user = new User();
        BeanUtils.copyProperties(param, user);

        // 加密密码
        user.setPassword(passwordEncoder.encode(param.getPassword()));

        // 设置默认状态
        user.setStatus(1);

        // 保存用户
        userMapper.insert(user);

        return user;
    }

    @Override
    public String login(UserLoginParam param) {
        try {
            // 直接查询用户并验证密码，避免使用AuthenticationManager导致的循环依赖
            User user = getUserByUsername(param.getUsername());
            if (user == null) {
                return null;
            }

            // 验证密码
            // 先尝试BCrypt验证，如果失败则尝试明文验证
            if (!passwordEncoder.matches(param.getPassword(), user.getPassword()) && !param.getPassword().equals(user.getPassword())) {
                return null;
            }

            // 创建UserDetails对象
            List<SimpleGrantedAuthority> authorities = new ArrayList<>();
            authorities.add(new SimpleGrantedAuthority("ROLE_USER"));
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                user.getUsername(),
                user.getPassword(),
                user.getStatus() == 1,
                true,
                true,
                true,
                authorities
            );

            // 生成JWT令牌
            return jwtTokenUtil.generateToken(userDetails);
        } catch (Exception e) {
            // 打印详细错误信息
            System.err.println("登录失败，详细错误: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public User getUserInfo(String username) {
        return getUserByUsername(username);
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean updatePassword(String username, UpdatePasswordParam param) {
        // 获取用户信息
        User user = getUserByUsername(username);
        if (user == null) {
            return false;
        }

        // 校验旧密码
        if (!passwordEncoder.matches(param.getOldPassword(), user.getPassword())) {
            return false;
        }

        // 更新密码
        user.setPassword(passwordEncoder.encode(param.getNewPassword()));
        userMapper.updateById(user);

        return true;
    }

    @Override
    public User updateUserInfo(String username, UpdateUserInfoParam param) {
        // 获取用户信息
        User user = getUserByUsername(username);
        if (user == null) {
            return null;
        }

        // 更新用户信息
        if (param.getNickname() != null) {
            user.setNickname(param.getNickname());
        }
        if (param.getPhone() != null) {
            user.setPhone(param.getPhone());
        }
        if (param.getEmail() != null) {
            user.setEmail(param.getEmail());
        }
        if (param.getGender() != null) {
            user.setGender(param.getGender());
        }
        if (param.getBirthday() != null) {
            user.setBirthday(param.getBirthday());
        }

        // 保存到数据库
        userMapper.updateById(user);

        return user;
    }

    @Override
    public BigDecimal getUserBalance(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return BigDecimal.ZERO;
        }
        return user.getBalance() != null ? user.getBalance() : BigDecimal.ZERO;
    }

    @Override
    @Transactional
    public BigDecimal operateBalance(Long userId, BalanceOperationParam param) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            return BigDecimal.ZERO;
        }

        // 获取当前余额
        BigDecimal currentBalance = user.getBalance() != null ? user.getBalance() : BigDecimal.ZERO;
        BigDecimal newBalance;

        // 根据操作类型处理余额
        if (param.getType() == 1) {
            // 充值
            newBalance = currentBalance.add(param.getAmount());
        } else if (param.getType() == 2) {
            // 提现
            if (currentBalance.compareTo(param.getAmount()) < 0) {
                // 余额不足
                return currentBalance;
            }
            newBalance = currentBalance.subtract(param.getAmount());
        } else {
            // 未知操作类型
            return currentBalance;
        }

        // 更新用户余额
        user.setBalance(newBalance);
        userMapper.updateById(user);

        return newBalance;
    }

    @Override
    @Transactional
    public boolean payOrder(Long userId, String orderNo) {
        // 获取订单信息
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_no", orderNo);
        queryWrapper.eq("user_id", userId);
        queryWrapper.eq("status", 0); // 待付款状态
        Order order = orderMapper.selectOne(queryWrapper);

        if (order == null) {
            return false;
        }

        // 获取用户信息
        User user = userMapper.selectById(userId);
        if (user == null) {
            return false;
        }

        // 获取订单金额信息
        BigDecimal totalAmount = order.getTotalAmount();
        BigDecimal promotionAmount = order.getPromotionAmount();
        BigDecimal payAmount = order.getPayAmount();

        // 确保优惠金额和支付金额有值
        if (promotionAmount == null) {
            promotionAmount = BigDecimal.ZERO;
        }

        if (payAmount == null) {
            payAmount = totalAmount.subtract(promotionAmount);
        }

        // 检查余额是否足够
        BigDecimal currentBalance = user.getBalance() != null ? user.getBalance() : BigDecimal.ZERO;
        if (currentBalance.compareTo(payAmount) < 0) {
            // 余额不足
            return false;
        }

        // 扣减余额
        BigDecimal newBalance = currentBalance.subtract(payAmount);
        user.setBalance(newBalance);
        userMapper.updateById(user);

        // 更新订单状态为待发货
        order.setStatus(1); // 待发货
        order.setPayTime(LocalDateTime.now());
        order.setPayType(1); // 余额支付
        orderMapper.updateById(order);

        return true;
    }
}
